<template>
	<el-card class="box-card" style="height: 100%">
		<el-container>
			<el-aside width="280px">
				<div class="chat-list">
					<el-tabs v-model="activeName" @tab-click="tabChange">
						<el-tab-pane label="当前会话" name="first">
							<div class="customer-list">
								<div
									v-for="(item, index) in customerList"
									:key="item.customer_id"
									:class="customerInfo.customer_id == item.customer_id ? 'chat-item  active' : 'chat-item'"
									@click="checkCustomer(item, index)">
									<div class="avatar">
										<img :src="item.avatar" />
										<div :class="item.online_status == 1 ? 'status' : 'status off'"></div>
									</div>
									<div class="user-info">
										<div class="hd">
											<span class="name line1">{{ item.customer_name }}</span>
										</div>
										<div class="bd line1">{{ item.last_word }}</div>
									</div>
									<div class="right-box">
										<div class="time">{{ item.time }}</div>
										<div class="num">
											<el-badge v-if="item.unread_msg > 0" :value="item.unread_msg" class="item"/>
										</div>
									</div>
								</div>
							</div>
						</el-tab-pane>
						<el-tab-pane label="历史会话" name="second">
							<div class="customer-list">
								<div
									v-for="(item, index) in customerLogList"
									:key="item.customer_id"
									:class="customerInfo.customer_id == item.customer_id ? 'chat-item  active' : 'chat-item'"
									@click="checkCustomer(item, index)">
									<div class="avatar">
										<img :src="item.avatar" />
										<div :class="item.online_status == 1 ? 'status' : 'status off'"></div>
									</div>
									<div class="user-info">
										<div class="hd">
											<span class="name line1">{{ item.customer_name }}</span>
										</div>
										<div class="bd line1"></div>
									</div>
									<div class="right-box">
										<div class="time">{{ item.time }}</div>
										<div class="num"></div>
									</div>
								</div>
							</div>
						</el-tab-pane>
					</el-tabs>
				</div>
			</el-aside>
			<el-main>
				<div class="chat-box">
					<div
						id="content-box"
						ref="content_box"
						style="height: calc(100% - 40px);padding: 20px;overflow-y: scroll;">
						<span class="get-more" @click="getMore" v-if="logPage.page < totalPages">加载更多</span>
						<div
							v-for="item in chatLog"
							:key="item.id"
							:class="item.from_id == nowUser ? 'chat-item right-box' : 'chat-item'">
							<div class="time">{{ item.time }}</div>
							<div class="flex-box">
								<div class="avatar">
									<img :src="item.from_id == nowUser ? nowAvatar : item.from_avatar">
								</div>
								<div class="msg-wrapper">
									<div v-if="item.msg_type == 'text'" class="txt-wrapper pad16">
										{{ item.content }}
									</div>
									<div class="img-wraper" v-if="item.msg_type == 'image'">
										<el-image :src="item.content" :preview-src-list="[item.content]"/>
									</div>
									<div class="img-wraper goods-card" v-if="item.msg_type == 'card'">
										<img :src="item.content.img"/>
										<span class="goods-title">{{ item.content.name }}</span>
										<span class="goods-price">￥ {{ item.content.price }}</span>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="chat-textarea">
					<div style="position: relative" v-show="showEmotion">
						<div class="face-div">
							<div class="face-item" v-for="item in emoji" :key="item" @click="face(item)">{{ item }}</div>
						</div>
					</div>
					<div class="chat-bar">
						<img :src="smileIcon" style="height: 20px;width: 20px;cursor: pointer;" @click="showFace" />
						<el-upload
							class="upload-demo"
							ref="uploadFile"
							:action="uploadUrl"
							:on-success="successHandle"
							style="margin-top: 10px;margin-left: 10px"
							:show-file-list="false"
							:limit="1">
							<img :src="picIcon" style="height: 20px;width: 20px;cursor: pointer;"/>
						</el-upload>
						<!--<i class="el-icon-info chat-log-icon"></i>-->
					</div>
					<div class="textarea-box">
						<textarea placeholder="输入内容" style="width: 99%;" v-model="content"></textarea>
						<div class="send-btn" @click="send('text')">
							<button type="button" class="el-button el-button--primary"><span>发送</span></button>
						</div>
					</div>
				</div>
			</el-main>
			<el-aside width="300px">
				<div class="customer-info">
					<div class="user-avatar" v-if="newCustomerBaseInfo.customerInfo">
						<img :src="newCustomerBaseInfo.customerInfo.customer_avatar" />
					</div>
					<div style="width: 100%;padding: 10px" v-if="newCustomerBaseInfo.customerInfo">
						<el-descriptions class="margin-top" :column="1" border>
							<el-descriptions-item label="用户名">
								{{ newCustomerBaseInfo.customerInfo.customer_name }}
							</el-descriptions-item>
							<el-descriptions-item label="手机号">
								{{ newCustomerBaseInfo.info.phone }}
							</el-descriptions-item>
							<el-descriptions-item label="注册时间">
								{{ newCustomerBaseInfo.info.register_time }}
							</el-descriptions-item>
							<el-descriptions-item label="累计下单数">
								{{ newCustomerBaseInfo.orderNum }}
							</el-descriptions-item>
							<el-descriptions-item label="累计支付金额">
								{{ newCustomerBaseInfo.orderPrice }}元
							</el-descriptions-item>
							<el-descriptions-item label="最近下单时间">
								{{ newCustomerBaseInfo.lastOrderTime }}
							</el-descriptions-item>
							<el-descriptions-item label="IP">
								{{ newCustomerBaseInfo.customerInfo.customer_ip }}
							</el-descriptions-item>
							<el-descriptions-item label="地区">
								{{ newCustomerBaseInfo.customerInfo.province }}{{ newCustomerBaseInfo.customerInfo.city }}
							</el-descriptions-item>
						</el-descriptions>
					</div>

				</div>
			</el-aside>
		</el-container>
	</el-card>
</template>

<script>
import config from "@/config"

export default {
	name: "chat",
	data() {
		return {
			pageLoading: true,
			activeName: 'first',
			socket: null,
			kefuInfo: {}, // 客服信息
			nowUser: "", // 当前客服的Code
			nowAvatar:"", // 当前客服的头像
			emoji: ["😀", "😃", "😄", "😁", "😆", "😅", "🤣", "😂", "🙂", "🙃", "😉", "😊", "😇", "🥰", "😍", "🤩", "😘", "😗", "😚", "😙", "😋", "😛", "😜", "🤪", "😝", "🤑", "🤗", "🤭", "🤫", "🤔", "🤐", "🤨", "😐", "😑", "😶", "😶‍🌫️", "😶‍🌫", "😏", "😒", "🙄", "😬", "😮‍💨", "🤥", "😌", "😔", "😪", "🤤", "😴", "😷", "🤒", "🤕", "🤢", "🤮", "🤧", "🥵", "🥶", "🥴", "😵", "😵‍💫", "🤯", "🤠", "🥳", "😎", "🤓", "🧐", "😕", "😟", "🙁", "☹️", "😮", "😯", "😲", "😳", "🥺", "😦", "😧", "😨", "😰", "😥", "😢", "😭", "😱", "😖", "😣", "😞", "😓", "😩", "😫", "🥱", "😤", "😡", "😠", "🤬", "😈", "👿", "💀", "☠️", "🤙🏻", "💩", "🤡", "👹", "👺", "👻", "💖"],
			content: '',
			showEmotion: false,
			onlineMap: [],
			customerList: [], // 服务的访客列表
			customerLogList: [], // 历史访客列表
			chatLog: [], // 聊天列表
			customerInfo: {}, // 访客信息
			logPage: {
				page: 1,
				limit: 15,
				customer_id: 0
			},
			totalPages: 0,
			newCustomerBaseInfo: {},
			nowIndex: 0,
			uploadUrl: config.API_URL + '/addons/chat/admin.Upload/uploadFile',
			smileIcon: config.API_URL + '/statics/images/smile.png',
			picIcon: config.API_URL + '/statics/images/picture.png'
		}
	},
	watch: {
		'$store.state.chat.customerIn': function () {
			let res = this.$store.state.chat.customerIn
			res.online_status = 1
			// console.log('在线数据', this.onlineMap, this.customerList, this.onlineMap.indexOf(res.customer_id), res.customer_id)
			if (this.onlineMap.length == 0) {
				this.onlineMap.push(parseInt(res.customer_id));
				this.customerInfo = res
				console.log('xxxx访客信息', res)
				this.customerList.push(res)

				this.getCustomerInfo()
				this.getChatLog()
			}

			let index = this.onlineMap.indexOf(res.customer_id)
			if (index == -1) {
				this.customerList.push(res)
			} else {
				this.customerList[index].online_status = 1
			}
		},
		'$store.state.chat.receiveMsg': function () {
			let res = this.$store.state.chat.receiveMsg

			if (res.from_id == this.customerInfo.customer_id) {
				if (res.msg_type == 'card') {
					try {
						res.content = JSON.parse(res.content)
					} catch (error) {
						console.log('xx', error)
					}
				}
				this.customerList[this.nowIndex].last_word = res.content
				this.chatLog.push(res)
			} else {

				let index = this.onlineMap.indexOf(res.from_id)
				if (index != -1) {
					this.customerList[index].unread_msg += 1
					this.customerList[index].last_word = res.content
				}
			}

			this.slide()
		},
		"$store.state.chat.customerOut": function () {
			let res = this.$store.state.chat.customerOut

			this.customerList.forEach((item, index) => {
				if (item.customer_id == res) {
					this.customerList[index].online_status = 0
				}
			})
		},
	},
	mounted() {
		this.getCustomerList()
		this.pageLoading = false

		let localUser = this.$TOOL.data.get("SELLER_USER_INFO")
		this.kefuInfo = {
			id: localUser.id,
			code: localUser.code,
			name: localUser.userName,
			avatar: localUser.avatar,
			seller_id: localUser.seller_id
		}

		this.nowUser = localUser.code
		this.nowAvatar = localUser.avatar
	},
	methods: {
		// 滑动
		slide() {
			this.$nextTick(() => {
				setTimeout(() => {
					document.getElementById("content-box").scrollTop =
						document.getElementById("content-box").scrollHeight;
				}, 200);
			});
		},
		// 获取列表
		async getCustomerList() {
			let res = await this.$API.chat.getCustomerList.get({type: this.activeName})
			if (this.activeName == 'first') {
				this.customerList = res.data

				this.onlineMap = [];
				res.data.forEach(item => {
					this.onlineMap.push(parseInt(item.customer_id))
				})

				// 默认选中第一个
				if (this.customerList.length > 0) {
					this.customerInfo = this.customerList[0]
					this.nowIndex = 0

					this.getCustomerInfo()
					this.getChatLog()
				}
			} else {
				this.customerLogList = res.data

				// 默认选中第一个
				if (this.customerLogList.length > 0) {
					this.customerInfo = this.customerLogList[0]
					this.nowIndex = 0

					this.getCustomerInfo()
					this.getChatLog()
				}
			}
		},
		// 选择访客
		checkCustomer(row, index) {
			this.customerInfo = row
			this.nowIndex = index

			if (this.activeName == 'first') {
				this.customerList[index].unread_msg = 0
			}

			this.getCustomerInfo()
			this.logPage.page = 1
			this.getChatLog()
		},
		// 获取聊天记录
		async getChatLog(type) {
			const loading = this.$loading({
				lock: true,
				text: "记录加载中...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.4)",
				target: document.querySelector("#content-box"),
			});
			this.logPage.customer_id = this.customerInfo.customer_id
			let res = await this.$API.chat.getChatLog.get(this.logPage)
			loading.close();

			if (type === 2) {
				this.chatLog = res.data.data.concat(this.chatLog);
			} else {
				this.chatLog = res.data.data;
				this.slide();
			}

			this.totalPages = res.data.last_page
			this.chatLog.forEach((item, index) => {
				if (item.msg_type == 'card') {
					try {
						this.chatLog[index].content = JSON.parse(item.content)
					} catch (error) {
						console.log('xx', error)
					}
				}
			})

		},
		// 获取用户信息
		async getCustomerInfo() {
			let res = await this.$API.chat.getCustomerInfo.get({customer_id: this.customerInfo.customer_id})
			this.newCustomerBaseInfo = res.data
		},
		// 选择图标
		face(item) {
			this.content += item
			this.showEmotion = false
		},
		// 展示
		showFace() {
			this.showEmotion = !this.showEmotion
		},
		// 消息发送
		send(msType) {
			if (
				this.content.length === 0 ||
				this.content.replace(/^\s*|\s*$/g, "") === ""
			) {
				this.$message.error("请输入内容");
				return;
			}

			const chatMessage = {
				from_id: this.kefuInfo.code,
				from_name: this.kefuInfo.name,
				from_avatar: this.kefuInfo.avatar,
				to_id: this.customerInfo.customer_id,
				to_name: this.customerInfo.customer_name,
				to_avatar: this.customerInfo.avatar,
				content: this.content,
				msg_type: msType,
			};

			this.$store.commit("SET_SEND_MESSAGE", chatMessage)
			chatMessage.time = this.getShortDate();
			this.content = "";
			this.chatLog.push(chatMessage);
			if (this.customerList[this.nowIndex]) {
				this.customerList[this.nowIndex].last_word = chatMessage.content
			}
			this.slide();
		},
		// 获取时间
		getShortDate() {
			const now = new Date()
			let month = now.getMonth() + 1
			if (month < 10) {
				month = '0' + month
			}
			let day = now.getDate()
			if (day < 10) {
				day = '0' + day
			}
			let hour = now.getHours()
			if (hour < 10) {
				hour = '0' + hour
			}
			let minutes = now.getMinutes()
			if (minutes < 10) {
				minutes = '0' + minutes
			}

			return month + '-' + day + ' ' + hour + ':' + minutes
		},
		// 上传成功回调
		successHandle(file) {
			this.content = file.data.url
			this.send('image')
		},
		// 加载更多
		getMore() {
			this.logPage.page++;
			if (this.logPage.page > this.totalPages) return;
			this.getChatLog(2);
		},
		// tab切换
		tabChange(val) {
			if (val.index == 1) {
				this.activeName = 'second'
				this.logPage.page = 1
				this.totalPages = 1
				this.chatLog = [];
			} else {
				this.activeName = 'first'
			}

			this.getCustomerList();
		}
	}
}
</script>

<style scoped>
.chat-list {
	border-right: 1px solid #ececec;
	background: #fff;
	height: calc(100vh - 30px);
}

.customer-info {
	border-left: 1px solid #ececec;
	background: #fff;
	height: calc(100vh - 30px);
}

.customer-list {
	width: 100%;
}

.customer-list .chat-item {
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-align: center;
	-ms-flex-align: center;
	align-items: center;
	-webkit-box-pack: justify;
	-ms-flex-pack: justify;
	justify-content: space-between;
	padding: 12px 10px;
	height: 74px;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	border-left: 3px solid transparent;
	cursor: pointer;
}

.customer-list .chat-item.active {
	background: #eff0f1;
	border-left: 3px solid #1890ff;
}

.chat-item .avatar {
	position: relative;
	width: 40px;
	height: 40px;
	display: block;
}

.avatar img {
	display: block;
	width: 100%;
	height: 100%;
	border-radius: 50%;
	border-style: none;
}

.avatar .status {
	position: absolute;
	right: 3px;
	bottom: 0;
	width: 8px;
	height: 8px;
	background: #48d452;
	border: 1px solid #fff;
	border-radius: 50%;
}

.chat-item .user-info {
	width: 155px;
	margin-left: 12px;
	margin-top: 5px;
	font-size: 16px;
	padding-top: 15px;
	padding-bottom: 10px;
}

.chat-item .user-info .hd {
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-align: center;
	-ms-flex-align: center;
	align-items: center;
	color: rgba(0, 0, 0, 0.65);
}

.chat-item .user-info .hd .name {
	max-width: 67%;
}

.line1, .line2 {
	overflow: hidden;
	text-overflow: ellipsis;
}

.line1 {
	white-space: nowrap;
}

.chat-item .user-info .hd .label.pc {
	background: rgba(100, 64, 194, 0.16);
	color: #6440c2;
}

.chat-item .user-info .hd .label {
	margin-left: 5px;
	color: #3875ea;
	font-size: 12px;
	background: #d8e5ff;
	border-radius: 2px;
	padding: 1px 5px;
}

.chat-item .user-info .bd {
	margin-top: 3px;
	font-size: 12px;
	color: #8e959e;
}

.chat-item .right-box {
	position: relative;
	-webkit-box-flex: 1;
	-ms-flex: 1;
	flex: 1;
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-ms-flex-direction: column;
	flex-direction: column;
	-webkit-box-align: end;
	-ms-flex-align: end;
	align-items: flex-end;
	color: #8e959e;
}

.customer-list .time {
	font-size: 12px;
}

.chat-item .right-box .num {
	margin-right: 12px;
	margin-top: 10px;
}

.chat-box {
	height: calc(100vh - 392px);
	background: #fff;
}

.content-box {
	height: calc(100% - 214px);
	padding: 20px;
	overflow-y: scroll;
}

.chat-box .chat-item {
	margin-bottom: 10px;
}

.chat-box .chat-item .time {
	text-align: center;
	color: #999;
	font-size: 14px;
	margin: 18px 0;
}

.chat-box .chat-item.right-box .flex-box {
	-webkit-box-orient: horizontal;
	-webkit-box-direction: reverse;
	-ms-flex-direction: row-reverse;
	flex-direction: row-reverse;
}

.chat-box .chat-item .flex-box {
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
}

.chat-box .chat-item.right-box .flex-box .avatar {
	margin-right: 0;
	margin-left: 16px;
}

.chat-box .chat-item .avatar {
	width: 40px;
	height: 40px;
	margin-right: 16px;
}

.chat-box .chat-item .avatar img {
	display: block;
	width: 100%;
	height: 100%;
	border-radius: 50%;
}

.chat-box .chat-item .msg-wrapper {
	max-width: 320px;
	background: #f5f5f5;
	border-radius: 10px;
	color: #000;
	font-size: 14px;
	overflow: hidden;
}

.chat-box .chat-item .msg-wrapper .pad16 {
	padding: 12px;
}

.chat-item .msg-wrapper .txt-wrapper {
	word-break: break-all;
}

.chat-box .chat-item .time {
	text-align: center;
	color: #999;
	font-size: 14px;
	margin: 18px 0;
}

.chat-box .chat-item .flex-box {
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
}

.chat-textarea {
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-ms-flex-direction: column;
	flex-direction: column;
	height: 214px;
	border-top: 1px solid #ececec;
}
.chat-bar {
	height: 50px;
	width: 100%;
	line-height: 50px;
	text-align: left;
	display: flex;
	align-items: center;
}
.iconfonts {
	font-family: "iconfont" !important;
	font-size: 16px;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}
.chat-textarea .textarea-box {
	-webkit-box-flex: 1;
	-ms-flex: 1;
	flex: 1;
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-ms-flex-direction: column;
	flex-direction: column;
	min-height: 0;
	position: relative;
}
.textarea-box textarea {
	height: 120px;
	resize: none;
	border: none;
	background: transparent;
	border-style: none;
	font-size: 14px;
	outline: none;
	padding: 0px 15px;
}
.send-btn {
	position: absolute;
	right: 0;
	bottom: 10px;
	display: -webkit-box;
	display: -ms-flexbox;
	display: flex;
	-webkit-box-pack: end;
	-ms-flex-pack: end;
	justify-content: flex-end;
	margin-top: 10px;
	margin-right: 10px;
}
.el-card__body {
	padding: 10px;
}
/* 隐藏滚动条 */
::-webkit-scrollbar {
	width: 6px;
}

/* 隐藏滚动条轨道 */
::-webkit-scrollbar-track {
	background-color: transparent;
}

/* 隐藏滚动条滑块 */
::-webkit-scrollbar-thumb {
	background-color: transparent;
}

/* 隐藏滚动条角落 */
::-webkit-scrollbar-corner {
	background-color: transparent;
}

.avatar .off {
	background: gray !important;
}
.goods-card {
	display: flex;
	flex-direction: column;
}
.goods-card img{
	width: 200px;
	height: auto;
}
.goods-card .goods-title {
	color: #111111;
	margin-bottom: 12px;
	display: block;
	font-size: 15px;
	overflow: hidden;
	text-overflow: ellipsis;
	word-break: break-all;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	width: 180px;
	padding: 0 10px 0 10px;
}
.goods-card .goods-price {
	font-size: 18px;
	padding: 0 10px 10px 10px;
	color: #e93323;
}

.user-avatar {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100px;
}

.user-avatar img {
	width: 80px;
	height: 80px;
}

.face-div {
	width: 400px;
	height: 200px;
	overflow: scroll;
	display: flex;
	flex-wrap: wrap;
	position: absolute;
	justify-content: space-between;
	z-index: 999;
	background: #fff;
	padding: 5px;
	top: -211px;
	border: 1px solid #e2e2e2;
}
.face-div .face-item {
	width: 30px;
	font-size: 20px;
	height: 30px;
	cursor: pointer;
}
.chat-log-icon {
	font-size: 20px; cursor: pointer; margin-left: 20px; color: rgb(51, 51, 51);display: flex;justify-content: center;align-items: center;
}
.pic-icon {
	font-size: 20px; cursor: pointer; margin-left: 20px; color: rgb(51, 51, 51);position: relative;top:2px;
}
.get-more {
	width: 60px;background: #f5f5f5;color: #909399;cursor: pointer;padding: 8px 5px;margin: 0 auto;display: block;font-size: 12px;text-align: center;
}
</style>
